<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2017/3/8
 * Time: 7:50
 */

namespace J\MVC;


/**
 * 部门处理中间件
 *
 */
class Department
{
    /**
     * @var string|bool 部门键
     */
    protected $department_key = false;

    /**
     * @var int 当前部门
     */
    protected $current_department = -1;

    /**
     * @var array 当前用户拥有权限的部门列表
     */
    protected $departments = [];

    /**
     * 构造函数
     * @param string|bool $key
     * @param [] $departments
     */
    public function __construct($key, $departments)
    {
        $this->department_key = $key;
        $this->departments = $departments;
    }

    public function isPromotion()
    {
        if(!$this->department_key) return true;

        return $this->validDepartment();
    }

    /**
     * @param int $current_department
     */
    public function setCurrentDepartment(int $current_department)
    {
        $this->current_department = $current_department;
    }

    /**
     * 当前部门必须通过请求传递
     *
     * @return int
     */
    public function getCurrentDepartment()
    {
        if($this->current_department <= 0){
            $this->current_department =  (int)(array_isset($_REQUEST,$this->department_key,
                array_isset($_REQUEST['search'], $this->department_key, 0))
            );
        }
        return $this->current_department;
    }

    public function getDepartments()
    {
        return $this->departments;
    }

    public function validDepartment($department = -1)
    {
        if($department === -1) $department = $this->getCurrentDepartment();

        return ($department > 0 and in_array($department,$this->departments));
    }

    public function remove($array)
    {
        $array = array_complete($array);
        unset($array[$this->department_key]);
        return $array;
    }

    public function add($array)
    {
        $array[$this->department_key] = $this->getCurrentDepartment();
        return $array;
    }

    public function  isDepartmentElement($field)
    {
        return ($this->department_key === $field);
    }
}